var path = require('path'),
  fs = require('fs');

function log(msg) {
  console.log(msg);
}

function write_file(filename, data) {
  fs.writeFile('./data/' + filename, typeof data == 'string' ? data : JSON.stringify(data), 'utf-8', function (err) {
    if (err) return log('写入文件失败: ' + filename + '   =>   ' + err.message);
    log('写入文件成功: ' + filename);
  });
}

var my_provs = ['北京','天津', '上海',  '重庆', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '四川', '贵州', '云南', '西藏', '陕西', '甘肃', '青海', '宁夏', '新疆', '香港', '澳门', '台湾'],
  map_prov_id = {};

my_provs.forEach(function (prov, i) {
  map_prov_id[prov] = i;
});

function parse_txt(texts) {
  var list_full = [],
    list_prov = [],
    map_prov = {},

    list_city_array = [],
    map_city_cn = {};

  (texts || '').split('\n').forEach(function (text) {
    if (!text || !/[a-zA-Z]+\d+(\s|,)/.test(text)) return;

    var vs = text.split(/\s+|,/),
      code = vs[0],                //城市/地区编码
      city_en = vs[1],             //英文名称
      city_cn = vs[2],             //中文名称
      country_code = vs[3],        //国家代码
      country_en = vs[4],          //国家英文名称
      country_cn = vs[5],          //国家中文名称
      prov_en = vs[6],             //省英文名称
      prov_cn = vs[7],             //省中文名称
      parent_city_en = vs[8],      //所属上级市英文名称
      parent_city_cn = vs[9],      //所属上级市中文名称
      lat = vs[10],                //纬度
      lon = vs[11];                //经度

    var data = {
      code: code,
      en: city_en,
      cn: city_cn,
      country_code: country_code,
      country_en: country_en,
      country_cn: country_cn,
      prov_en: prov_en,
      prov_cn: prov_cn,
      pcity_en: parent_city_en,
      pcity_cn: parent_city_cn,
      lon: lon,
      lat: lat
    };

    if (!map_prov[prov_cn]) {
      list_prov.push(prov_cn);
      map_prov[prov_cn] = true;
    }

    //list_city_array.push([code, city_cn, parent_city_cn != city_cn ? parent_city_cn : '', prov_cn != parent_city_cn ? prov_cn : '']);

    var list_city = map_city_cn[city_cn];
    if (!list_city) map_city_cn[city_cn] = list_city = [];
    list_city.push(data);

    if (list_city.length > 1) log(list_city.map(function (data) { return data.prov_cn + data.pcity_cn + data.cn + ' - ' + data.code }).join(' | '));

    list_full.push(data);
  });

  var list = [], map_subs = {};

  list_full.forEach(function (data) {
    var ps = map_city_cn[data.pcity_cn], pdata;
    if (ps.length <= 0) {
      log('无父级城市数据: ' + data.code + '  |  ' + data.cn);
      return;
    }

    if (ps.length == 1) {
      pdata = ps[0];
    } else {
      ps.forEach(function (_data) {
        if (_data.prov_cn == data.prov_cn) {
          pdata = _data;
          return false;
        }
      });
      //log(data.cn + '  =>  ' + pdata.prov_cn + pdata.pcity_cn + (pdata.cn != pdata.pcity_cn ? pdata.cn : ''));
    }

    var city = { id: data.code, cn: data.cn }, pid = pdata.code;
    if (city.id == pid) city.pcn = data.prov_cn;
    else city.pid = pid;

    var pkey = city.pid || city.pcn;

    if (pkey) {
      var list_sub = map_subs[pkey];
      if (!list_sub) map_subs[pkey] = list_sub = [];

      list_sub.push([list_sub.length, city.cn, city.id]);

      // if (city.id == 'CN101011500') {
      //   console.log('---------------------- ' + city.cn + ' -----------------------');
      //   console.log(pkey);
      //   console.log(list_sub);
      //   console.log('');
      // }
    }

    list_city_array.push([city.id, city.cn, pkey]);

    list.push(city);
  });

  log('\n');

  var dataAll = { countries: [[0, '中国']], '0': [] }, last_prov_id = my_provs.length - 1;

  list_prov.forEach(function (prov, i) {
    var prov_id = map_prov_id[prov];
    if (prov_id == undefined) prov_id = ++last_prov_id;

    //dataAll['0'].push([prov_id, prov]);
    dataAll['0'][prov_id]=[prov_id, prov];

    var sub_citys = map_subs[prov];
    dataAll['0_' + prov_id] = sub_citys;

    sub_citys.forEach(function (c) {
      var sub_areas = map_subs[c[2]];
      if (!sub_areas || sub_areas.length <= 0) return log('无城区数据:' + JSON.stringify(c));

      dataAll['0_' + prov_id + '_' + c[0]] = sub_areas;
    });
  });

  //write_file('citys.json', { provs: list_prov, citys: list_city_array });
  //write_file('china-city-list.json', { provs: list_prov, citys: list });
  //write_file('china-city-list.full.json', list_full);
  write_file('full-citys.json', dataAll);
}

function init() {
  //var fullpath = path.resolve('./china-city-list.txt');
  var fullpath = path.resolve('./source/china-city-list.csv');
  if (!fs.existsSync(fullpath)) return log('文件不存在: ' + fullpath);

  fs.readFile(fullpath, function (err, data) {
    if (err) return log('读取文件错误: ' + err.message);

    parse_txt(data + '');
  });
}

init();